/* =======================================================================
 * jQuery.Huipreview.js v2.2 图片预览
 * http://www.h-ui.net/
 * Created & Modified by guojunhui
 * Date modified 2024.09.13
 * Copyright 2017-2024 郭俊辉 All rights reserved.
 * Licensed under MIT license.
 * http://opensource.org/licenses/MIT
 * 功能介绍：当用户将鼠标悬停在小图上时，会显示一个更大的图片预览。
 * 使用方法：
   $('.your-element-class').Huipreview();
 * ========================================================================*/
!function($) {
  $.fn.Huipreview = function(options){
    // 确保 options 是一个对象，如果不是则初始化为空对象
    options = (typeof options === 'object' && options !== null) ? options : {};

    var defaults = {
      className: "active",
      bigImgWidth: 300,
    };
    var settings = $.extend({}, defaults, options);
    this.each(function(){
      var that = $(this);
      var timer;

      that.hover(
        function() {
          clearTimeout(timer);
          timer = setTimeout(function () {
            $("#preview-wrapper").remove();
            var smallImg = that.find("img").attr("src");
            var bigImg = that.attr('data-src');
            var winW = $(window).width();
            var winW5 = winW / 2;
            var imgT = that.parent().offset().top;
            var imgL = that.parent().offset().left;
            var imgW = that.parent().width();
            var ww = (imgL + imgW / 2);
            var tooltipLeft = "auto",tooltipRight = "auto";
            if (ww < winW5) {
              tooltipLeft = (imgW + imgL) + "px";
            } else {
              tooltipRight = (winW - imgL) + "px";
            }
            
            that.addClass(settings.className);
            if (bigImg == '') {
              return false;
            } else {  
              var tooltip_keleyi_com = 
              '<div id="preview-wrapper" style="position: absolute;z-index:999;width:'+settings.bigImgWidth+'px;height:auto;top:' + imgT + 'px;right:' + tooltipRight + ';left:' + tooltipLeft + '">'+
                '<img src="'+smallImg+'" width="'+settings.bigImgWidth+'">'+
              '</div>';
              $("body").append(tooltip_keleyi_com);

              /*图片预加载*/
              var image = new Image();
              image.src = bigImg;
              /*创建一个Image对象*/
              image.onload = function() {
                $('#preview-wrapper').find("img").attr("src",bigImg).css("width", settings.bigImgWidth);
              };
            }
          },500);
        },
        function() {
          clearTimeout(timer);
          that.removeClass(settings.className);
          $("#preview-wrapper").remove();
        }
      );
    });
  }
} (window.jQuery);